const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const path = require("path");
const {
  checkFileList,
  getFileList,
  saveFile,
  openFileSave,
  openFileByPath,
} = require("./handlers");
const { buildAppMenu, buildDockMenu, showContextMenu } = require('./menus/index.js')

const isMac = process.platform === "darwin";
const devURL = "http://localhost:5173";

let currentFile = {}

// 自动更新
// require('update-electron-app')({
//   repo: 'https://github.com/WDFM/markdown-editor..git',
//   updateInterval: '30 minutes'
// })

let mainWindow = null

// 是否通过拖动文件到dock打开
let openFileData = null

const createWindow = () => {
  mainWindow = new BrowserWindow({
    icon: path.join(__dirname, '../build/icons/logo.png'),
    webPreferences: {
      devTools: !app.isPackaged,
      contextIsolation: false,
      nodeIntegration: true
    },
  });

  if (app.isPackaged) {
    mainWindow.loadFile(path.join(__dirname, "../dist/index.html"));
    // mainWindow.webContents.openDevTools();
  } else {
    mainWindow.loadURL(devURL);
    mainWindow.webContents.openDevTools();
  }
  
  // 菜单
  buildAppMenu(mainWindow)
};

// 处理拖动文件到dock打开
app.on('open-file', (event, filePath) => {
  const file = openFileByPath(filePath)
  if (file) openFileData = file

  if (mainWindow?.webContents?.send) {
    mainWindow.webContents.send('open-file-by-path', openFileData)
    openFileData = null
  }
})

app.whenReady().then(() => {
  createWindow()
  buildDockMenu()
  // 设置为默认打开md的程序
  app.setAsDefaultProtocolClient('md')

  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (!isMac) app.quit();
});

// 启动时打开文件
ipcMain.on("open-file-on-start", () => {
  if (openFileData) {
    mainWindow.webContents.send('open-file-by-path', openFileData)
    openFileData = null
  }
})

// 检查文件列表是否存在
ipcMain.on("check-file-list", (args, files) => {
  // console.log(files);
  mainWindow.webContents.send("check-file-list", checkFileList(files));
});

// 根据文件列表返回文件信息列表，同时排除不存在的文件
ipcMain.on("get-file-list", (args, fileList = []) => {
  const list = checkFileList(fileList);
  mainWindow.webContents.send("get-file-list", getFileList(list));
  console.log("get-file-list, done");
});

// 保存文件
ipcMain.on("save-file", async (args, path, fileData) => {
  const res = await saveFile(path, fileData);
  mainWindow.webContents.send("save-file", res);
});

// 打开文件
ipcMain.on("open-file-menu", () => {
  if (!app.applicationMenu) return
  const openFileMenu = app.applicationMenu.getMenuItemById("openFile");
  openFileMenu.click();
});

// 新建文件并保存
ipcMain.on("save-new-file", async (args, file) => {
  const res = await openFileSave(mainWindow, file);
  mainWindow.webContents.send("save-new-file", res);
});

// 右键菜单
ipcMain.on('context-menu', () => {
  showContextMenu(mainWindow)
})

// 文件发生变化时，设置窗口的关闭按钮是否是未保存状态
ipcMain.on('file-changed', (args, file) => {
  // console.log(file)
  currentFile = file
  mainWindow.setDocumentEdited(file.tempData !== file.fileData)
})

// 退出应用
ipcMain.on('quit-app', () => {
  app.quit()
})

// 根据文件路径打开文件
ipcMain.on('open-file-by-path', (args, filePath) => {
  const file = openFileByPath(filePath)
  mainWindow.webContents.send('open-file-by-path', file)
})

// 监听历史文件列表变化，并同步系统的最近打开文件列表
ipcMain.on('history-changed', (args, history) => {
  if (history.length === 0) return
  app.clearRecentDocuments()
  history.map(v => {
    if (v.path) app.addRecentDocument(v.path)
  })
})

// 测试
ipcMain.on("test-fn", (args, params) => {
  // mainWindow.webContents.send('test-fn', process.argv)
});

// 拦截退出，判断文档是否保存
app.on('before-quit', async e => {
  if (currentFile.fileData !== currentFile.tempData) {
    const res = dialog.showMessageBoxSync(mainWindow, {
      type: 'warning',
      title: '提示',
      message: '您的修改还未保存，是否保存？',
      buttons: ['保存', '放弃保存', '取消'],
      defaultId: 0,
      cancelId: 2,
    })
    // 保存并关闭
    if (res === 0) {
      const res = await saveFile(currentFile.path, currentFile.fileData);
      mainWindow.webContents.send('save-file-menu', res, true)
    }
    if (res === 2) {
      e.preventDefault()
    }
  }
})